package com.ungao.framework.scanner;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;

public class PackageScanner {

    /**
     * 扫描包路径
     *
     * @param scanPackage
     * @return
     */
    public List<String> scanPackage(String scanPackage) {
        List<String> classNames = new CopyOnWriteArrayList(new ArrayList());
        URL url = PackageScanner.class.getClassLoader().getResource(scanPackage.replaceAll("\\.", "/"));
        File classPath = new File(url.getFile());
        for (File file : classPath.listFiles()) {
            if (file.isDirectory()) {
                classNames.addAll(scanPackage(scanPackage + "." + file.getName()));
            } else {
                if (file.getName().endsWith("class")) {
                    String className = (scanPackage + "." + file.getName()).replace(".class", "");
                    classNames.add(className);
                }
            }
        }
        return classNames;
    }

    /**
     * 扫描配置文件
     *
     * @param contextConfigLocation
     */
    public Properties scanConfig(String contextConfigLocation) {
        final Properties contextConfig = new Properties();
        try (InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation)) {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return contextConfig;
    }
}
